package com.leyou.gateway.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

@Configuration
@EnableConfigurationProperties(CORSProperties.class)
public class GlobalCORSConfig {

    /*@Autowired
    private CORSProperties prop;*/

    @Bean
    public CorsFilter corsFilter(CORSProperties prop){
        //跨域配置信息
        CorsConfiguration config = new CorsConfiguration();
        //1 允许跨域的资源（url）
        /*List<String> allowedOrigins = prop.getAllowedOrigins();
        for (String allowedOrigin : allowedOrigins) {
            config.addAllowedOrigin(allowedOrigin);
        }*/
        prop.getAllowedOrigins().forEach(config::addAllowedOrigin);

        //2是否发送Cookie信息
        config.setAllowCredentials(prop.getAllowedCredentials());
        // 3 允许的请求方式
        prop.getAllowedMethods().forEach(config::addAllowedMethod);
        // 4 允许的头信息
        prop.getAllowedHeaders().forEach(config::addAllowedHeader);
        // 5 设置允许跨域请求的最大有效时间
        config.setMaxAge(prop.getMaxAge());

        //配置跨域拦截资源路径
        UrlBasedCorsConfigurationSource configSource = new UrlBasedCorsConfigurationSource();
        configSource.registerCorsConfiguration(prop.getFilterPath(),config);
        return new CorsFilter(configSource);
    }

}
